package com.limingru.online_class.utils;

import com.limingru.online_class.common.Constant;
import com.limingru.online_class.domain.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JWTUtil {
    /**
     * 密钥
     */
    private static final String SECRET = "limingru";

    /**
     * 主题
     */
    private static final String SUBJECT = "online_class";

    /**
     * 生成 token
     */
    public static String generateJWT(User user) {
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_img", user.getHeadImg())
                .claim("id", user.getId())
                .claim("name", user.getName())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + Constant.EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
        return token;
    }

    /**
     * 校验 token
     */
    public static Claims checkToken(String token) {
        try {
            Claims body = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
            return body;
        } catch (Exception e) {
            return null;
        }
    }
}
